use axum::{extract::Query, http::StatusCode, response::IntoResponse, routing, Json, Router};

use tracing::info;

use crate::vo::KeywordQuery;

pub struct ProductsController {
    routes: Router,
}

impl Into<Router> for ProductsController {
    fn into(self) -> Router {
        self.routes
    }
}

impl ProductsController {
    pub fn init() -> Self {
        let routes = Router::new().route("/products", routing::get(search_products));

        Self { routes }
    }
}

async fn search_products(Query(keyword_query): Query<KeywordQuery>) -> impl IntoResponse {
    info!(keyword = keyword_query.keyword(), "search products");
    let response_products = {
        if let Some(keyword) = keyword_query.keyword() {
            crate::products::get()
                .iter()
                .filter(|&p| p.name.to_lowercase().contains(&(keyword.to_lowercase())))
                .collect::<Vec<_>>()
        } else {
            crate::products::get().iter().collect::<Vec<_>>()
        }
    };
    let products_length = response_products.len();
    info!(
        fetched_length = ?products_length,
        "retrieved {} products", products_length
    );
    (StatusCode::OK, Json(response_products))
}
